package com.lyq.interaction.controller;

import com.lyq.interaction.model.Result;
import com.lyq.interaction.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Value("${saveSessionPhotoPath}")
    private String saveSessionPhotoPath; //保存聊天图片的路径

    @Resource
    private MessageService messageService;
    /**
     * 获取sessionID会话的历史消息，按时间降序从start+1开始获取10条
     * @param sessionId
     * @param start
     * @return
     */
    @RequestMapping("/getHistoryMessage")
    public Object getHistoryMessage(Integer sessionId, Integer start) {
        log.info("获取会话的历史消息 sessionId: {} start: {}", sessionId, start);
        return messageService.getHistoryMessage(sessionId, start);
    }
    @RequestMapping("/savePhoto")
    public Object savePhoto(@RequestPart("file") MultipartFile file) {
        log.info("保存聊天图片：{}", file.toString());
        String fileType = "image/png".equals(file.getContentType()) ? ".png" : ".jpg";
        //将图片保存起来
        String uuid = "";
        String path = "";
        String ret = "";
        //保存图片
        try {
            while (true) {
                uuid = UUID.randomUUID().toString().replaceAll("-", "");
                path = saveSessionPhotoPath+uuid+fileType;
                ret = "messagePhoto/"+uuid+fileType;
                File test = new File(path);
                if (!test.isFile()) {
                    break;
                }
            }
            file.transferTo(new File(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(ret);
    }
}
